package com.gs.wzmanager.controller;

import com.gs.wzmanager.entity.Resource;
import com.gs.wzmanager.entity.Role;
import com.gs.wzmanager.service.ResourceService;
import com.gs.wzmanager.service.RoleService;
import com.gs.wzmanager.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    private Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity add(@RequestBody Role role) {
        roleService.addRole(role);
        return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
    }

    @RequestMapping("/listView")
    public String listView(){
        return "role/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public List list() {
        List<Role> roles = roleService.queryAllRole();
        return roles;
    }

    @RequestMapping("/res/{roleId}")
    @ResponseBody
    public Map res(@PathVariable int roleId) {
        Role role = roleService.queryRoleById(roleId);
        List<Resource> resources = roleService.queryResourceByRoleId(roleId);
        Map map = new HashMap();
        map.put("role",role);
        map.put("resList",resources);
        return map;
    }

    @RequestMapping("/res/update/{roleId}")
    @ResponseBody
    public Map updateRes(@PathVariable int roleId) {
        Role role = roleService.queryRoleById(roleId);
        List<Resource> resources = resourceService.queryAllResource();
        List<Resource> role_res = roleService.queryResourceByRoleId(roleId);

        Map map = new HashMap();
        map.put("role",role);
        map.put("roleRes",role_res);
        map.put("resList",resources);

        return map;
    }

    @RequestMapping(value = "/delete/{roleId}", method = RequestMethod.GET)
    public ResponseEntity del(@PathVariable int roleId) {
        roleService.deleteRole(roleId);
        return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseEntity update(@RequestBody Role role) {
        roleService.updateRole(role);
        return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
    }
}
